<template>
  <el-form 
        :model="form" 
        ref="form"
        :rules="rules" 
        class="form">

        <el-form-item class="form-item" prop="username">
            <el-input 
            placeholder="用户名/手机"
            v-model="form.username"
            @focus="hideErrMsg('username')">
            </el-input>
        </el-form-item>

        <el-form-item class="form-item" prop="password">
            <el-input 
            placeholder="密码" 
            type="password" v-model="form.password">
            </el-input>
        </el-form-item>

        <p class="form-text">
            <nuxt-link to="#">忘记密码</nuxt-link>
        </p>

        <el-button 
        class="submit"
        type="primary"
        @click="handleLoginSubmit">
            登录
        </el-button>
  </el-form>
</template>

<script>
import {login} from './user'
export default {
  data () {
    return {
      form:{
        username:'13800138000',
        password:'123456'
      },
      rules:{
        username:[
          {
            required:true,message:'请输入用户名/手机',trigger: "blur"
          }
        ],
        password:[
          {
            required:true,message:'请输入密码',trigger: "blur"
          },
          {
            min:6,message:'密码最少6位',trigger: "blur"
          },
        ],
      }
    }
  },
  methods: {
    // 清理表单错误信息
    hideErrMsg(aa){
        // 当输入框聚焦需要清理当前输入项的错误提示
        // 优化体验
        // 拿到当前 form 对象
        // 调用里面 clearValidate 函数
        // 传入希望清理的 prop
      this.$refs.form.clearValidate(aa)
    },
    // 提交登录
    handleLoginSubmit(){
      // 验证表单
      this.$refs.form.validate(async valid =>{
        if(valid){
          const res = await login(this.form)
          console.log(res);
          if(res && res.data.token){
            this.$message.success('登录成功')
            this.$store.commit('userstore/setUserInfo',res.data)
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
    .form{
        padding:25px;
    }

    .form-item{
        margin-bottom:20px;
    }

    .form-text{
        font-size:12px;
        color:#409EFF;
        text-align: right;
        line-height: 1;
    }

    .submit{
        width:100%;
        margin-top:10px;
    }
</style>